import router from '@/router'
import axios from 'axios'
import { Message } from 'element-ui'
import store from '../store'
import { getTimeStamp } from './auth'

// 登陆超时的时间
const TimeOut = 3600;
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 5000  //定义5秒超时
}) // 创建一个axios的实例
// Add a request interceptor
service.interceptors.request.use(function (config) {
    // Do something before request is sent
    if (store.getters.token) {
      config.headers['Authorization']=`Bearer ${store.getters.token}`;
      if (ischeckTimeOut()) {
        store.dispatch("user/loginout");
        router.push("/login")
        return Promise.reject(Message.error("登陆身份失效,请重新登陆"))
      }
    }
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

service.interceptors.response.use(function (response) {
    const {success, message, data} = response.data;
    if ( success ) {
        return data
    } else {
        Message.error(message);
        return Promise.reject(new Error(message))
    }
},
 function (error) {
     if (error.response && error.response.data && error.response.data.code === 10002) {        
        store.dispatch("user/loginout")
        router.push("/login")
        Message.error("登陆身份失效,请重新登陆")
     } else {
        Message.error(error.message);
     }
     
     return Promise.reject(error)
 }
) // 响应拦截器

function ischeckTimeOut () {
  // console.log(1,"ischeck");
  const nowTime = Date.now();
  const timeStamp = getTimeStamp();
  return (nowTime - timeStamp ) / 1000 > TimeOut
}

export default service // 导出axios实例
